//
//  testViewController.m
//  iOS_Router_Runtime
//
//  Created by 王水鑫 on 2018/10/26.
//  Copyright © 2018年 王水鑫. All rights reserved.
//

#import "testViewController.h"
#import <WebKit/WebKit.h>
#import "PAMailDetailHeadCell.h"
#import "PAMailDetailSubjectCell.h"
#import "PAMailDetailAuthorityCell.h"
#import "SXImageViewPage.h"
#import "SXCustomNavigationStyleManager.h"
#import "SXDataConvertManager.h"
#import "SXNetworkManager.h"
#import "SXDataCheckManager.h"
#import "SXDataManager-umbrella.h"

@interface testViewController ()<UITableViewDelegate, UITableViewDataSource, WKNavigationDelegate, WKUIDelegate, SXNetworkManagerDelegate>
@property (retain, nonatomic) UITableView *containerTableView;
@property (strong, nonatomic) WKWebView *webView;
@property (assign, nonatomic) CGFloat webViewHeight;
@property (assign, nonatomic) CGFloat recordOriginWebViewHeight;
@property (strong, nonatomic) PAMailDetailHeadCell *headCell;
@property (strong, nonatomic) PAMailDetailSubjectCell *subjectCell;
@property (strong, nonatomic) PAMailDetailAuthorityCell *authorityCell;
@property (strong, nonatomic) UITableViewCell *webCell;
@property (assign, nonatomic) CGFloat headCellHeight;
@property (assign, nonatomic) BOOL lockAuthority;

@end

@implementation testViewController
#pragma mark - SXNetworkManagerDelegate
- (void)SXNetworkManagerRunning:(BOOL)isRunning {
    if (isRunning) {
        self.navigationItem.titleView = [SXCustomNavigationStyleManager customDynamicTitleViewWhenFetchDataFromServerWithTitleText:@"收取中"];
        return;
    }
    self.navigationItem.titleView = nil;
}
- (void)SXNetworkManagerSuccessReturnJsonResponse:(NSDictionary *)response urlPath:(NSString *)urlPath parameters:(NSDictionary *)parameters {
    NSLog(@"网络请求返回数据:%@", response);
    NSLog(@"当前线程：%@", [NSThread currentThread]);
}
- (void)SXNetworkManagerExecuteErrorPromptInsteadOfLoadingAnimation:(NSString *)message {
    NSLog(@"超时:%@", message);
    
}
//-(void)startNewThread{
//    //获取当前线程的runloop对象
//    NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
//    //结构体
//    CFRunLoopObserverContext  context = {0, (__bridge void *)(self), NULL, NULL, NULL};
//    //创建runloop观察者，绑定run loop。
//    CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
//                                                            kCFRunLoopAllActivities, YES, 0,myRunLoopObserver, &context);
//    if (observer)
//    {
//        CFRunLoopRef cfLoop = [myRunLoop getCFRunLoop];//获取Core Foundation形式的runloop引用
//        //为run loop的默认的模式添加观察者
//        CFRunLoopAddObserver(cfLoop, observer, kCFRunLoopDefaultMode);
//    }
//    // Create and schedule the timer.
//    [NSTimer scheduledTimerWithTimeInterval:1 target:self
//                                   selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
//    // NSTimer * timer = [NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//
//    //     NSLog(@"纯净的定时器");
//    //}];
//    //[myRunLoop addTimer:timer forMode:NSDefaultRunLoopMode];
//    [myRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
//}
- (void)runloopTest {
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    {
//        NSThread *testThread = [[NSThread alloc] initWithTarget:self selector:@selector(runloopTest) object:nil];
//    }
    NSMutableArray *testArray = [NSMutableArray arrayWithArray:@[@{@"key":@"1"}, @{@"key":@"1"}, @{@"key":@"1"}, @{@"key":@"e"}, @{@"key":@"eb"}, @{@"key":@"b"}, @{@"key":@"be"}, @{@"key":@"a"}, @{@"key":@"eb"}]];
    NSMutableArray *remTagArray = [NSMutableArray array];
    for (NSDictionary *dict in testArray) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"key CONTAINS[cd] %@", dict[@"key"]];
        NSArray *remArray = [testArray filteredArrayUsingPredicate:predicate];
        if (remArray.count > 1) {
            [remTagArray addObject:remArray[0]];
        }
    }
    for (int i = 0; i < remTagArray.count; i ++) {
        [testArray removeObject:remTagArray[i]];
        [testArray addObject:remTagArray[i]];
    }
    
    NSLog(@"数组:%@", testArray);
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"邮件详情";
    UIColor *color = [UIColor redColor];
    NSDictionary *titleDictionary = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = titleDictionary;
    NSLog(@"交换后调用？%@", [SXGetBundleData dataPathForImageName:@"filter"]);
    SXNetworkManager *networkManager = [SXNetworkManager new];
    networkManager.errorPrompt = @"请求失败";
    [SXNetworkManager launchPostRequestToRemoteServerWithURLPath:@"/api/file/uploadbase64" parameters:@{@"key":@"主键"} delegate:self managerObject:networkManager];
    NSLog(@"汉字拼音:%@", [SXDataConvertManager convertToPinyinFromChineseCharacters:@"测试拼音@￥WAITforfake"]);
    NSLog(@"汉语声调：%@", [SXDataConvertManager convertToPinyinToneFromChineseCharacters:@"汉语声调 fakss 有对对对jfjf 123@qq.com"]);
    NSLog(@"汉字转成拼音:%@", [SXDataConvertManager getPinYinPrefixLetterFromChineseCharacters:@"测试拼音 @#WAITforfake"]);
    NSLog(@"是否是邮件:%d", [SXDataCheckManager checkNormalEmailFormatFromString:@"ffff@pinan.com.cn"]);
//    NSArray *images = @[[UIImage imageNamed:@"launch1"], [UIImage imageNamed:@"launch2"], [UIImage imageNamed:@"launch3"], [UIImage imageNamed:@"launch4"]];
//    SXImageViewPage *viewPage = [[SXImageViewPage alloc] initComponentFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) WithImages:images WithType:SXImageViewPage_LaunchImageViewSimple];
//    [self.view addSubview:viewPage];
    [self drawTableViewContainer];
    
    [self setwebCell];
}
- (void)drawTableViewContainer {
    self.lockAuthority = NO;
    self.containerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.containerTableView.delegate = self;
    self.containerTableView.dataSource = self;
    self.containerTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//去多余cell
    [self.view addSubview:self.containerTableView];
    self.headCell = [[PAMailDetailHeadCell alloc] init];
    self.headCell.senderNameLab.text = @"发件人是谁（sss）";
    self.headCell.receiverNameLab.text = @"收件人:fjeiajf、aefawf等2人";
    __weak typeof(self) weakSelf = self;
    self.headCell.switchDetailInfo = ^(BOOL showDetail, CGFloat cellHeight) {
        weakSelf.headCellHeight = cellHeight;
        [weakSelf.containerTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        if (showDetail) {
            NSLog(@"展示详情,行高改变！行高：%f", cellHeight);
        } else {
            NSLog(@"行高恢复70px！行高：%f", cellHeight);
        }
    };
    self.subjectCell = [[PAMailDetailSubjectCell alloc] init];
    self.subjectCell.mailTitleLab.text = @"固定主题";
    self.subjectCell.timeLab.text = @"时间错e测试眼神字体";
    self.authorityCell = [[PAMailDetailAuthorityCell alloc] init];
    self.webCell = [UITableViewCell new];
}
- (void)setwebCell {
    NSString *htmlString = @"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><style type=\"text/css\">body, td { font: 14px/1.5 Helvetica,Microsoft YaHei; } body, p, div {word-wrap: break-word;} p{margin:5px 0;} table {border-collapse:collapse;} img {border:0;} </style></head><body><img id=\"1\" src=\"/Users/wangshuixin/Desktop/id=AAMkAGIyNDhiN2Y1LTBiNTAtNDk1Yi1iYWVjLWNhZjEzOTdlMzYzMgBGAAAAAAATWXfjteDlSbmVBKnUveZLBwCOQxV4ctSrRYvyihnTeNpKAAAAyDZAAABWefcLwbu1QqkBp2V4RJChAADLPPGhAAA=&attid=0&cps=1.png\" paicfs=\"237923\">1测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城223333333测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城测试能有都城</body></html>";
    //注入JS以缩放网页，避免获取到的网页高度远超实际高度，出现超长空白页面
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width - 20, 400) configuration:wkWebConfig];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.scrollView.delegate = self; // 监听捏合缩放
    self.webView.scrollView.scrollEnabled = YES;
    //开了支持滑动返回
    self.webView.allowsBackForwardNavigationGestures = NO;
    // 禁止webview的弹跳，防止跟tableview滑动手势冲突
    self.webView.scrollView.bounces = NO;
    
    [self.webCell addSubview:self.webView];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    [self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"file:///"]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4 + 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            return self.headCellHeight ? : 70;
            break;
        case 1:
            return 70;
            break;
        case 2:
            if (self.lockAuthority) {
                return 38;
            }
            return 0;
            break;
        case 3:
            NSLog(@"web高度%f", self.webViewHeight);
            return self.webViewHeight ? : 400;
            break;
        default:
            return 60;
            break;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 3:
            {
                return self.webCell;
            }
            break;
        case 2:
        {
            if (self.lockAuthority) {
                return self.authorityCell;
            }
            UITableViewCell *cell = [UITableViewCell new];
            return cell;
        }
            break;
        case 1:
            return self.subjectCell;
            break;
        case 0:
            return self.headCell;
            break;
        default:
        {
            UITableViewCell *cell = [UITableViewCell new];
            cell.backgroundColor = [UIColor greenColor];
            return cell;
        }
            break;
    }
}
#pragma mark - UIScrollviewDelegate
// 监听webView的scrollview缩放事件
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    
    //    CGRect themeFrame = self.themeView.frame; // themeView的 origin frame
    //    CGRect receiverFrame = self.receiverView.frame; // receiverView的 origin frame
    //    CGFloat offsetY = self.originFrame.origin.y - (scrollView.contentOffset.y >= 0 ? scrollView.contentOffset.y : 0); // 去掉缩小偏移问题
    //    self.themeView.frame = CGRectMake(0, offsetY + self.headerContentHeightConstraint.constant, themeFrame.size.width, themeFrame.size.height);
    //    self.receiverView.frame = CGRectMake(0, offsetY, receiverFrame.size.width, receiverFrame.size.height);
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.webView.scrollView) {
        NSLog(@"webview的scrollview滑动");
    } else if (scrollView == self.containerTableView) {
        NSLog(@"tableview的scrollview滑动");
    }
}
#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题，动态改变
//    self.title = webView.title;
    __block CGFloat webViewHeight;
    __weak typeof(self) weakSelf = self;
    //获取内容实际高度（像素）@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度，看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;")，但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度，并重置webview的frame
        webViewHeight = [result doubleValue];
        weakSelf.webViewHeight = webViewHeight;
        weakSelf.recordOriginWebViewHeight = webViewHeight;
        NSLog(@"高度：%f", webViewHeight);
        [weakSelf.containerTableView reloadData];
        webView.frame = CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width - 20, webViewHeight);
    }];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
//    self.title = webView.title;
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
}

@end
